package handler

import (
	"github.com/eatmoreapple/openwechat"
	"log"
	"strings"
	"wechat/gpt/client/api"
)

type groupMessageHandler struct {
}

// NewGroupMessageHandler 创建群消息处理器
func NewGroupMessageHandler() IMessageHandler {
	return &groupMessageHandler{}
}

// handle 处理消息
func (this *groupMessageHandler) handle(msg *openwechat.Message) error {
	if msg.IsText() {
		return this.replyText(msg)
	}
	return nil
}

// ReplyText 发送文本消息到群
func (this *groupMessageHandler) replyText(msg *openwechat.Message) error {
	// 接收群消息
	sender, err := msg.Sender()
	group := openwechat.Group{User: sender}

	// 记录消息
	log.Printf("received group from : %v\nmessage : %v", group.NickName, msg.Content)

	// 不是@的则不处理
	if !msg.IsAt() {
		return nil
	}

	// 获取@我的用户
	groupSender, err := msg.SenderInGroup()
	if err != nil {
		log.Printf("get at msg sender in group error : %v\n", err)
		return err
	}
	atText := "@" + groupSender.NickName + " "

	if userSession.ClearUserSessionContext(sender.ID(), msg.Content) {
		_, err = msg.ReplyText(atText + "下一个问题")
		if err != nil {
			log.Printf("response user error: %v \n", err)
		}
		return nil
	}

	// 替换掉@文本 设置会话上下文
	requestText := buildRequestText(sender, msg)
	if requestText == "" {
		return nil
	}

	reply, err := api.Call(requestText)
	if err != nil {
		log.Printf("call gpt error : %v\n", err)
		_, _ = msg.ReplyText("出现错误")
		return err
	}

	// 如果询问结果为空则直接返回
	if reply == "" {
		return nil
	}

	// 整理数据
	reply = strings.TrimSpace(reply)
	reply = strings.Trim(reply, "\n")

	// 设置上下文缓存
	userSession.SetUserSessionContext(sender.ID(), requestText, reply)

	// 回复@我的用户
	replyText := atText + reply
	_, err = msg.ReplyText(replyText)
	if err != nil {
		log.Printf("reply at group error : %v \n", err)
	}

	return err
}

// buildRequestText 构建请求GPT的文本
func buildRequestText(sender *openwechat.User, msg *openwechat.Message) string {

	// 替换掉at信息 整理数据
	replaceText := "@" + sender.Self.NickName
	requestText := strings.TrimSpace(strings.ReplaceAll(msg.Content, replaceText, ""))
	if requestText == "" {
		return ""
	}

	// 读取缓存上下文
	requestText = userSession.GetUserSessionContext(sender.ID()) + requestText

	return requestText
}
